<template>
  <div class="min-h-screen w-full bg-gray-50 p-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="mb-10">
        <h1 class="text-3xl font-bold text-gray-900">岗位管理</h1>
        <p class="mt-2 text-gray-600">查看并管理所有发布的职位信息</p>
      </div>

      <!-- 筛选控制区（沿用你原来的 query 与事件） -->
      <div class="bg-white rounded-xl shadow-sm p-6 mb-8">
        <div class="flex flex-wrap items-center gap-6">
          <!-- 岗位名称搜索 => query.title -->
          <div class="flex-1 min-w-[200px]">
            <label class="block text-sm font-medium text-gray-700 mb-2">岗位名称</label>
            <div class="relative">
              <input
                v-model="query.title"
                placeholder="请输入岗位名称"
                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition"
                @keyup.enter="handleSearch"
              />
              <div class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                <el-icon><Search /></el-icon>
              </div>
            </div>
          </div>

          <!-- 发布状态筛选 => query.status（仍用 1/0/2：上线/下线/草稿） -->
          <div class="relative">
            <label class="block text-sm font-medium text-gray-700 mb-2">发布状态</label>
            <el-select v-model="query.status" placeholder="请选择状态" class="w-48" clearable>
              <el-option label="全部状态" :value="''" />
              <el-option label="上线" :value="1" />
              <el-option label="下线" :value="0" />
              <el-option label="草稿" :value="2" />
            </el-select>
          </div>

          <!-- 城市码 => query.cityCode -->
          <div class="relative">
            <label class="block text-sm font-medium text-gray-700 mb-2">城市码</label>
            <el-input v-model="query.cityCode" placeholder="如 310115" class="w-48" clearable />
          </div>

          <!-- 搜索按钮 -->
          <div class="self-end pb-1">
            <button
              class="!rounded-button whitespace-nowrap bg-blue-600 hover:bg-blue-700 text-white px-6 py-2.5 text-sm font-medium transition-colors flex items-center"
              @click="handleSearch"
            >
              <el-icon class="mr-1"><Search /></el-icon>
              搜索
            </button>
          </div>

          <!-- 发布岗位按钮 -->
          <div class="self-end pb-1">
            <button
              class="!rounded-button whitespace-nowrap bg-green-600 hover:bg-green-700 text-white px-6 py-2.5 text-sm font-medium transition-colors flex items-center"
              @click="openCreate"
            >
              <el-icon class="mr-1"><Plus /></el-icon>
              发布岗位
            </button>
          </div>
        </div>
      </div>

      <!-- 批量操作栏（仅前端选择，不影响你原本后端逻辑） -->
      <div class="bg-white rounded-xl shadow-sm p-4 mb-6 flex items-center justify-between">
        <div class="flex items-center">
          <el-checkbox v-model="selectAll" @change="handleSelectAll" class="mr-4">全选</el-checkbox>
          <span class="text-gray-600 text-sm mr-6">已选择 {{ selectedIds.length }} 项</span>

          <div class="flex gap-3">
            <button
              class="!rounded-button whitespace-nowrap border border-gray-300 bg-white text-gray-700 px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors flex items-center"
              :disabled="selectedIds.length === 0"
              :class="{ 'opacity-50 cursor-not-allowed': selectedIds.length === 0 }"
              @click="batchUpdateStatus(1)"
            >
              <el-icon class="mr-1"><Upload /></el-icon>
              批量上线
            </button>

            <button
              class="!rounded-button whitespace-nowrap border border-gray-300 bg-white text-gray-700 px-4 py-2 text-sm font-medium hover:bg-gray-50 transition-colors flex items-center"
              :disabled="selectedIds.length === 0"
              :class="{ 'opacity-50 cursor-not-allowed': selectedIds.length === 0 }"
              @click="batchUpdateStatus(0)"
            >
              <el-icon class="mr-1"><CircleClose /></el-icon>
              批量下线
            </button>
          </div>
        </div>

        <div class="text-sm text-gray-500">
          共 {{ total }} 个岗位
        </div>
      </div>

      <!-- 岗位信息卡片列表（数据仍来自 tableData，loading 与空状态保留） -->
      <el-skeleton :loading="loading" animated :rows="6">
        <template #default>
          <div v-if="tableData.length" class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div
              v-for="row in tableData"
              :key="row.id"
              class="bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-md transition-shadow duration-300"
            >
              <div class="p-6">
                <div class="flex items-start">
                  <!-- 勾选 -->
                  <div class="pt-1 mr-4">
                    <el-checkbox
                      :model-value="selectedIds.includes(row.id)"
                      @update:model-value="val => handleRowSelect(val, row.id)"
                    />
                  </div>

                  <!-- 内容 -->
                  <div class="flex-1">
                    <div class="flex justify-between items-start">
                      <div>
                        <h3 class="text-lg font-semibold text-gray-900" :title="row.title">{{ row.title || '未命名岗位' }}</h3>
                        <p class="text-sm text-gray-500 mt-1">{{ row.category || '-' }}</p>
                      </div>

                      <el-tag :type="getStatusType(row.status)" size="small" class="ml-4">
                        {{ getStatusText(row.status) }}
                      </el-tag>
                    </div>

                    <div class="mt-4 grid grid-cols-2 gap-4">
                      <div>
                        <p class="text-xs text-gray-500">发布时间</p>
                        <p class="text-sm font-medium text-gray-900 mt-1">{{ formatTime(row.publishTime) }}</p>
                      </div>
                      <div>
                        <p class="text-xs text-gray-500">投递人数</p>
                        <p class="text-sm font-medium text-gray-900 mt-1">{{ row.applicantCount ?? '-' }} 人</p>
                      </div>
                    </div>

                    <div class="mt-4 grid grid-cols-2 gap-4">
                      <div>
                        <p class="text-xs text-gray-500">地点</p>
                        <p class="text-sm font-medium text-gray-900 mt-1" :title="row.location">{{ row.location || '-' }}</p>
                      </div>
                      <div>
                        <p class="text-xs text-gray-500">薪资</p>
                        <p class="text-sm font-medium text-gray-900 mt-1">
                          <template v-if="row.salaryMin || row.salaryMax">
                            {{ row.salaryMin || '-' }} ~ {{ row.salaryMax || '-' }} {{ unitText(row.salaryUnit) }}
                          </template>
                          <template v-else>-</template>
                        </p>
                      </div>
                    </div>

                    <!-- 标签 -->
                    <div v-if="parseTags(row.tags).length" class="mt-4 flex flex-wrap gap-2">
                      <el-tag
                        v-for="(t, i) in parseTags(row.tags)"
                        :key="i"
                        size="small"
                        effect="plain"
                      >
                        {{ t }}
                      </el-tag>
                    </div>

                    <!-- 操作 -->
                    <div class="mt-6 flex justify-between items-center">
                      <button
                        class="!rounded-button whitespace-nowrap text-blue-600 hover:text-blue-800 text-sm font-medium flex items-center"
                        @click="openEdit(row)"
                      >
                        <el-icon class="mr-1"><View /></el-icon>
                        查看 / 编辑
                      </button>

                      <!-- 状态切换按钮（上线<->下线；草稿另行选择） -->
                      <div class="flex items-center gap-3">
                        <el-dropdown trigger="click">
                          <span class="el-dropdown-link text-sm text-gray-600 hover:text-gray-800 cursor-pointer">上下线</span>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item @click="handleChangeStatus(row,1)">上线</el-dropdown-item>
                              <el-dropdown-item @click="handleChangeStatus(row,0)">下线</el-dropdown-item>
                              <el-dropdown-item @click="handleChangeStatus(row,2)">草稿</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>

                        <button
                          v-if="row.status !== 2"
                          class="!rounded-button whitespace-nowrap px-3 py-1.5 text-xs font-medium flex items-center"
                          :class="row.status === 1
                            ? 'bg-red-50 text-red-600 hover:bg-red-100'
                            : 'bg-green-50 text-green-600 hover:bg-green-100'"
                          @click="toggleRowStatus(row)"
                        >
                          <el-icon class="mr-1">
                            <Close v-if="row.status === 1" />
                            <Check v-else />
                          </el-icon>
                          {{ row.status === 1 ? '下线岗位' : '上线岗位' }}
                        </button>

                        <el-popconfirm title="确认删除该岗位？" @confirm="handleDelete(row)">
                          <template #reference>
                            <el-button size="small" type="danger" text>删除</el-button>
                          </template>
                        </el-popconfirm>
                      </div>
                    </div>
                  </div>
                </div>
              </div> <!-- /p-6 -->
            </div>
          </div>

          <!-- 空状态 -->
          <div v-else class="text-center py-16">
            <div class="mx-auto h-24 w-24 text-gray-300 mb-4">
              <el-icon class="text-6xl"><Document /></el-icon>
            </div>
            <h3 class="text-lg font-medium text-gray-900 mb-1">暂无匹配岗位</h3>
            <p class="text-gray-500">尝试调整筛选条件或创建新岗位</p>
          </div>
        </template>
      </el-skeleton>

      <!-- 分页（逻辑不变） -->
      <div class="mt-6 flex justify-end">
        <el-pagination
          :current-page="query.pageNo"
          :page-size="query.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,30,50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 弹窗 -->
      <JobPostForm ref="formRef" @success="onFormSuccess" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import * as ElementPlus from 'element-plus'
import JobPostForm from './JobPostForm.vue'
import { pageJobPosts, deleteJobPost, changeJobPostStatus, updateJobPostState } from '@/api/business/jobpost'
import { Search, Plus, View, Upload, CircleClose, Check, Close, Document } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const companyId = route.query.companyId

const ElMessage = (ElementPlus as any).ElMessage
type Row = any

const loading = ref(false)
const tableData = ref<Row[]>([])
const total = ref(0)
const formRef = ref<InstanceType<typeof JobPostForm> | null>(null)

// ✅ 沿用你原有的查询对象与逻辑
const query = reactive({
  pageNo: 1,
  pageSize: 10,
  title: '',
  cityCode: '',
  status: '' as any, // '' | 0 | 1 | 2
  companyId: companyId || null // 添加companyId筛选条件
})

const unitText = (u?: number) => (u === 2 ? '元/年' : u === 3 ? '元/天' : '元/月')

/** 过滤空参数，避免把 '' 传给后端导致查询条件失效 */
const cleanParams = (obj: Record<string, any>) => {
  const out: Record<string, any> = {}
  Object.keys(obj).forEach(k => {
    const v = (obj as any)[k]
    if (v !== '' && v !== undefined && v !== null) out[k] = v
  })
  return out
}

/** 时间显示：0/空 显示 '-'；数值时间戳自动兼容秒/毫秒 */
const formatTime = (timestamp: number | string) => {
  if (!timestamp || timestamp === 0) return '-'
  if (typeof timestamp === 'number') {
    const date = timestamp > 9999999999 ? new Date(timestamp) : new Date(timestamp * 1000)
    return date.toLocaleString()
  }
  return timestamp
}

/** tags 兼容：string[] / JSON 字符串 / null */
const parseTags = (val: any): string[] => {
  if (Array.isArray(val)) return val as string[]
  if (typeof val === 'string' && val.trim()) {
    try { const arr = JSON.parse(val); return Array.isArray(arr) ? arr : [] } catch { return [] }
  }
  return []
}

/** 仍然使用你原有的取数方式（不改 index.ts） */
const fetchPage = async () => {
  loading.value = true
  try {
    const resp = await pageJobPosts(cleanParams(query) as any)
    const page = resp?.data ?? resp
    tableData.value = (page?.list ?? page?.records ?? page?.rows ?? []) as Row[]
    total.value = (page?.total ?? page?.totalCount ?? page?.count ?? 0) as number
  } finally {
    loading.value = false
  }
}

const handleSearch = () => { query.pageNo = 1; fetchPage() }
const resetQuery = () => { query.title = ''; query.cityCode = ''; query.status = '' as any; query.pageNo = 1; fetchPage() }

const openCreate = () => formRef.value?.open('create')
const openEdit = (row: Row) => formRef.value?.open('update', row)

/** 状态显示（仍然按 1/0/2） */
const getStatusText = (s: number) => (s === 1 ? '上线' : s === 0 ? '下线' : '草稿')
const getStatusType = (s: number) => (s === 1 ? 'success' : s === 0 ? 'info' : 'warning')

/** 单行快捷切换（上线<->下线） */
const toggleRowStatus = async (row: Row) => {
  // 确定目标状态：当前是上线(1)则改为下线(0)，否则上线(1)
  const targetStatus = row.status === 1 ? 0 : 1;
  
  // 调用统一的更新状态接口，传递完整的 JobPostVO 数据
  const data: any = { ...row, status: targetStatus };
  await updateJobPostState(data);
  
  ElMessage.success(targetStatus === 1 ? '岗位已上线' : '岗位已下线');
  fetchPage();
}

/** 删除保持不变 */
const handleDelete = async (row: Row) => {
  await deleteJobPost(row.id)
  ElMessage.success('删除成功')
  if (tableData.value.length === 1 && query.pageNo > 1) query.pageNo--
  fetchPage()
}

/** 表单保存成功后刷新 */
const onFormSuccess = () => {
  if (!formRef.value?.editingId) query.pageNo = 1
  fetchPage()
}

/** 分页（不变） */
const handleSizeChange = (val: number) => { query.pageSize = val; fetchPage() }
const handleCurrentChange = (val: number) => { query.pageNo = val; fetchPage() }

/** —— 前端批量选择（仅影响 UI，不改变后端接口逻辑） —— */
const selectAll = ref(false)
const selectedIds = ref<number[]>([])

const handleSelectAll = () => {
  if (selectAll.value) {
    selectedIds.value = tableData.value.map((r: Row) => r.id)
  } else {
    selectedIds.value = []
  }
}
const handleRowSelect = (checked: boolean, id: number) => {
  if (checked) {
    if (!selectedIds.value.includes(id)) selectedIds.value.push(id)
  } else {
    selectedIds.value = selectedIds.value.filter(x => x !== id)
  }
  // 同步全选状态（仅对当前页）
  selectAll.value = selectedIds.value.length > 0 && selectedIds.value.length === tableData.value.length
}

/** 批量上下线 */
const batchUpdateStatus = async (status: 0 | 1) => {
  if (!selectedIds.value.length) return
  
  // 批量操作，需要先获取完整数据再调用 updateJobPostState 接口
  const promises = selectedIds.value.map(async id => {
    // 在当前页面数据中查找对应的岗位数据
    const row = tableData.value.find(item => item.id === id)
    if (row) {
      const data: any = { ...row, status: status }
      return updateJobPostState(data)
    }
    // 如果在当前页面找不到，则只传递 id 和 status
    return updateJobPostState({ id, status })
  })
  await Promise.all(promises)
  
  ElMessage.success(status === 1 ? '批量上线成功' : '批量下线成功')
  selectedIds.value = []
  selectAll.value = false
  fetchPage()
}

// 如果需要在组件加载时就使用这个参数
onMounted(() => {
  fetchPage() // 修复调用函数的语法错误
  if (companyId) {
    // 使用 companyId 进行业务处理
    console.log('接收到的公司ID:', companyId)
  }
})
</script>

<style scoped>
/* Element 组件的小样式对齐 */
:deep(.el-select) { width: 100%; }
:deep(.el-tag) { border: none; font-weight: 500; }
</style>
